<template>
  <div class="property">
    <el-scrollbar class="property-scrollbar">
      <div class="property-title">配置</div>
      <el-collapse class="property-collapse" v-model="collapseName">
        <el-collapse-item title="全局配置" name="global">
          <el-form v-model="globalConfig" label-position="top">
            <el-form-item label="分辨率">
              <el-input-number
                v-model="globalConfig.resolutionRatio[0]"
                controls-position="right"
                style="width: 100px"
                step-strictly
                :min="0"
              >
                <template #prefix>w</template>
                <template #decrease-icon>
                  <el-icon>
                    <Minus />
                  </el-icon>
                </template>
                <template #increase-icon>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </template>
              </el-input-number>
              <el-input-number
                v-model="globalConfig.resolutionRatio[1]"
                controls-position="right"
                style="width: 100px"
                class="ml10"
                step-strictly
                :min="0"
              >
                <template #prefix>h</template>
                <template #decrease-icon>
                  <el-icon>
                    <Minus />
                  </el-icon>
                </template>
                <template #increase-icon>
                  <el-icon>
                    <Plus />
                  </el-icon>
                </template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="比例" prop="radio">
              <el-text>{{ globalConfig.radio }}</el-text>
            </el-form-item>
            <el-form-item label="网格" prop="griddling">
              <el-input-number
                v-model="globalConfig.griddling"
                class="property-input"
                step-strictly
                :min="10"
              />
            </el-form-item>
            <el-form-item label="网格颜色" prop="griddling">
              <el-input
                v-model="globalConfig.griddlingColor"
                class="property-input"
                type="color"
              >
                <template #append>
                  {{ globalConfig.griddlingColor }}
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item title="基础属性" name="base">
          <div v-show="formData && formData.w && formData.h">
            <el-form v-model="formData" label-position="top">
              <el-form-item label="组件名称" prop="name">
                <el-input
                  v-model="formData.name"
                  class="property-input"
                  @focus="handleFocus"
                ></el-input>
              </el-form-item>
              <el-form-item label="尺寸" prop="w">
                <el-input-number
                  v-model="formData.w"
                  controls-position="right"
                  style="width: 100px"
                  @focus="handleFocus"
                  step-strictly
                  :min="10"
                  :max="globalConfig.resolutionRatio[0]"
                >
                  <template #prefix>w</template>
                </el-input-number>
                <el-input-number
                  v-model="formData.h"
                  controls-position="right"
                  style="width: 100px"
                  class="ml10"
                  @focus="handleFocus"
                  step-strictly
                  :min="10"
                  :max="globalConfig.resolutionRatio[1]"
                >
                  <template #prefix>h</template>
                </el-input-number>
              </el-form-item>

              <el-form-item label="位置" prop="y">
                <el-input-number
                  v-model="formData.y"
                  controls-position="right"
                  style="width: 100px"
                  @focus="handleFocus"
                  step-strictly
                  :min="0"
                  :max="maxY"
                >
                  <template #prefix>y</template>
                </el-input-number>
                <el-input-number
                  v-model="formData.x"
                  controls-position="right"
                  style="width: 100px"
                  @focus="handleFocus"
                  step-strictly
                  :min="0"
                  :max="maxX"
                >
                  <template #prefix>x</template>
                </el-input-number>
              </el-form-item>
            </el-form>
          </div>
          <div v-show="!formData || !formData.w">
            <el-empty description="请选择组件" :image-size="80" />
          </div>
        </el-collapse-item>
        <el-collapse-item
          title="数据源管理"
          name="source"
          v-show="formData.config?.isShowSourceConfig"
        >
          <sourceList v-model="formData"></sourceList>
        </el-collapse-item>
        <el-collapse-item title="高级配置" name="config">
          <component
            :is="panelComponentsList[formData.config?.key]"
            v-model="formData"
            ref="asyncComponentRef"
          ></component>
        </el-collapse-item>
        <el-collapse-item title="图层" name="layer">
          <TransitionGroup
            class="property-layout"
            v-show="layoutList.length"
            @dragover="handleDragOver"
            @drop="handleDrop"
            @dragenter="handleDragEnter"
            @dragend="handleDragEnd"
            ref="dragParentRef"
            tag="div"
            name="drag"
          >
            <div
              v-for="item in layoutList"
              :key="item.id"
              :id="item.id"
              draggable="true"
              @dragstart="handleDragstart($event, item)"
              @click="layoutClick(item)"
              :class="{
                'property-layout-list': true,
                active: item.active,
              }"
            >
              <div class="list-title">
                {{ item.name }}
              </div>
              <div class="list-icon" @click="layoutDelete(item)">
                <el-icon><Delete /></el-icon>
              </div>
            </div>
          </TransitionGroup>
          <el-empty
            v-show="!layoutList.length"
            description="请添加组件"
            :image-size="80"
          />
        </el-collapse-item>
      </el-collapse>
    </el-scrollbar>
  </div>
</template>
<script setup>
import { toRefs, ref, watch, watchEffect } from 'vue'
import { getGcd, loadComponents } from '../utils'
import useDesignStore from '@/store/modules/baseDesign'
import sourceList from './base/sourceList.vue'
let props = defineProps({
  formData: {
    type: Object,
    default: () => {},
  },
  globalConfig: {
    type: Object,
    default: () => {},
  },
})
let asyncComponentRef = ref()
let { globalConfig } = toRefs(props)
let collapseName = ref(['global', 'base', 'layer', 'config', 'source'])
let dragParentRef = ref()
let targetIndex = null
let { formData } = toRefs(props)
let emits = defineEmits([
  'updateProperty',
  'updateLayout',
  'updateGlobalConfig',
])
let layoutList = ref([])
// 加载组件
let panelComponentsList = loadComponents()
let maxY = ref(0)
let maxX = ref(0)

watchEffect(() => {
  layoutList.value = useDesignStore().getLayoutList
})
watch(
  () => formData.value,
  newVal => {
    if (newVal) {
      maxY.value =
        globalConfig.value.resolutionRatio[1] - newVal.h > 0
          ? globalConfig.value.resolutionRatio[1] - newVal.h
          : 0
      maxX.value =
        globalConfig.value.resolutionRatio[0] - newVal.w > 0
          ? globalConfig.value.resolutionRatio[0] - newVal.w
          : 0

      emits('updateProperty', newVal)
    }
  },
  {
    deep: true,
  },
)
watch(
  () => globalConfig.value,
  newVal => {
    if (newVal) {
      let gcd = getGcd(newVal.resolutionRatio[0], newVal.resolutionRatio[1])
      newVal.radio = `${newVal.resolutionRatio[0] / gcd}:${newVal.resolutionRatio[1] / gcd}`
      emits('updateGlobalConfig', newVal)
    }
  },
  {
    deep: true,
  },
)

// 图层点击
let layoutClick = item => {
  item.active = true
  emits('updateLayout', item)
}
// 图层删除
let layoutDelete = item => {
  item.delete = true
  item.advancedConfig.delete = true
  emits('updateProperty', item)
}
let sourceNode = null
// 图层层级切换开始拖拽
let handleDragstart = function (event, res) {
  event.dataTransfer.setData('propertyData', JSON.stringify(res))
  event.dataTransfer.effectAllowed = 'move'

  setTimeout(() => {
    event.target.classList.add('moving')
  }, 0)
  sourceNode = event.target
}
// 拖拽
let handleDrop = event => {
  event.dataTransfer.effectAllowed = 'move'
  let data = event.dataTransfer.getData('propertyData')
  try {
    let subassemblyData = JSON.parse(data)
    // 删除拖拽元素
    for (let i = 0; i < layoutList.value.length; i++) {
      if (layoutList.value[i].id == subassemblyData.id) {
        layoutList.value.splice(i, 1)
        i--
        break
      }
    }
    layoutList.value.splice(targetIndex, 0, subassemblyData)
    layoutList.value.map((item, index) => {
      return (item.z = index)
    })
  } catch (err) {
    console.error(err)
  }
}
// 拖拽结束
let handleDragOver = e => {
  e.dataTransfer.dropEffect = 'move'
  e.preventDefault()
  // 设置允许放置
}
// 拖拽进入
let handleDragEnter = e => {
  e.preventDefault()
  if (e.target === dragParentRef.value || e.target === sourceNode) {
    return
  }
  layoutList.value.forEach((item, index) => {
    if (item.id === e.target.id) {
      targetIndex = index
    }
  })
}
let handleDragEnd = e => {
  e.target.classList.remove('moving')
}
let handleFocus = () => {
  formData.value.active = true
}
</script>
<style scoped>
.property {
  width: 250px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  background: #fff;
}
.property-title {
  padding: 6px;
  box-sizing: border-box;
  border-bottom: 1px solid #ccc;
  background: #f8f8f8;
}
.property-input {
  width: 190px;
}
.property-collapse {
  border: none;
}
:deep(.el-collapse-item__header) {
  padding-left: 16px;
  box-sizing: border-box;
}

.property-scrollbar {
  height: calc(100vh - 62px);
  background: #fff;
  padding-bottom: 16px;
  box-sizing: border-box;
}
.property-layout {
  display: flex;
  flex-direction: column;
  row-gap: 16px;
  padding: 0 16px;
  box-sizing: border-box;
}
.property-layout-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid transparent;
  padding: 6px;
  box-sizing: border-box;
  cursor: move;
}
.property-layout-list:hover {
  background: rgba(64, 158, 255, 0.1);
}
.property-layout-list.active {
  border: 1px solid #409eff;
}
.property-layout-list.moving {
  border: 1px dashed #ddd;
  color: transparent;
  background: transparent;
}
.list-icon {
  cursor: pointer !important;
}
.drag-move, /* 对移动中的元素应用的过渡 */
.drag-enter-active,
.drag-leave-active {
  transition: all 0.5s ease;
}

.drag-enter-from,
.drag-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 确保将离开的元素从布局流中删除
  以便能够正确地计算移动的动画。 */
.drag-leave-active {
  position: absolute;
}
</style>
